<script lang="tsx">
import { defineComponent, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Bell, Search } from '@vben/icons';
import { UserDropdown } from '@vben/layouts';
import { ElInput } from 'element-plus';
// import loginTitle from '#/assets/images/login-title.png';
import { useMessage } from '#/hooks/useMessage';
import { useUserDropdown } from '#/hooks/useUserDropdown';
import { VbenIconButton } from '@vben-core/shadcn-ui';
import { useGlobalSearch } from '#/views/home/hooks/useGlobalSearch';
import { useUserStore } from '@vben/stores';
import SearchSuggestion from './search-suggestion.vue';
import { useRecentSearch } from './hooks/useRecentSearch';
import { useSearchAnalytics } from './hooks/useSearchAnalytics';
import { DEFAULT_HOME_PATH } from '#/utils/constants';
export default defineComponent({
  name: 'HomeLayout',
  setup() {
    const { showDot } = useMessage();
    const router = useRouter();
    const route = useRoute();
    const searchKeyword = ref('');
    const { emitSearch } = useGlobalSearch();
    const userStore = useUserStore();

    // 搜索建议相关状态
    const searchContainerRef = ref<HTMLElement>();
    const showSearchSuggestion = ref(false);
    const { addRecentSearch } = useRecentSearch();
    const { trackSearch } = useSearchAnalytics();

    // 使用 UserDropdown hooks
    const {
      isLogin,
      userDropdownProps,
      handleLogout
    } = useUserDropdown({
      showPersonalCenter: true,
      showAdminMenu: route.path !== '/test/explainCore'
    });

    const handleTitleClick = () => {
      router.push(DEFAULT_HOME_PATH);
    };

    // 处理消息图标点击事件
    const handleMessageClick = () => {
      router.push('/lesson/personalCenter/userMessage');
    };

    // 处理搜索
    const handleSearch = () => {
      const keyword = searchKeyword.value.trim();
      if (keyword) {
        // 添加到最近搜索
        addRecentSearch(keyword);
        // 发送搜索埋点
        trackSearch(keyword);
        // 通过全局搜索 Hook 触发搜索事件，供其他页面/组件监听
        emitSearch(keyword);
        // 隐藏搜索建议
        showSearchSuggestion.value = false;
      }
    };

    // 处理搜索框回车事件
    const handleSearchEnter = () => {
      handleSearch();
    };

    // 处理搜索框获得焦点
    const handleSearchFocus = () => {
      showSearchSuggestion.value = true;
    };

    // 处理搜索建议选择
    const handleSearchSelect = (keyword: string) => {
      searchKeyword.value = keyword;
      handleSearch();
    };


    // 判断菜单项是否为当前激活状态
    const isActiveRoute = (routePath: string) => {
      return route.path === routePath || route.path.startsWith(routePath + '/');
    };

    // 获取菜单项样式类
    const getMenuItemClass = (routePath: string) => {
      const baseClass = "py-[6px] px-[24px] text-[16px] leading-[24px] transition-all duration-200 relative group";
      const activeClass = "font-medium";
      const inactiveClass = "text-gray-600";

      return `${baseClass} ${isActiveRoute(routePath) ? activeClass : inactiveClass}`;
    };

    return () => (
      <div class="bg-white border-b border-gray-200">
        <div class="flex items-center justify-between h-[64px] px-[32px]">
          {/* 左侧：Logo + 导航菜单 */}
          <div class="flex items-center">
            {/* Logo区域 */}
            <div
              class="flex items-center h-full cursor-pointer transition-all duration-300 hover:bg-blue-50 rounded-lg"
              onClick={handleTitleClick}
            >
              <img src={userStore.tenant?.loginUrl} alt="logo" class="h-10 w-10" />
              <span class="ml-[8px] text-lg font-[500] text-gray-800">
                {userStore.tenant?.shortName}
              </span>
            </div>

            {/* 导航菜单 */}
            <nav class="hidden md:flex items-center ml-[24px]">
              {/* <button
                class={getMenuItemClass('/homePage/homePageIndex')}
                onClick={() => router.push('/homePage/homePageIndex')}
              >
                首页
                <span class={`absolute bottom-0 left-1/2 transform -translate-x-1/2 h-0.5 bg-blue-600 transition-all duration-200 ${isActiveRoute('/homePage/homePageIndex') ? 'w-5' : 'w-0 group-hover:w-5'}`}></span>
              </button> */}
              <button
                class={getMenuItemClass('/homePage/homePageCourse')}
                onClick={() => router.push('/homePage/homePageCourse')}
              >
                课程中心
                <span class={`absolute bottom-0 left-1/2 transform -translate-x-1/2 h-0.5 bg-blue-600 transition-all duration-200 ${isActiveRoute('/homePage/homePageCourse') ? 'w-5' : 'w-0 group-hover:w-5'}`}></span>
              </button>
              <button
                class={getMenuItemClass('/homePage/homePageTenant')}
                onClick={() => router.push('/homePage/homePageTenant')}
              >
                认证中心
                <span class={`absolute bottom-0 left-1/2 transform -translate-x-1/2 h-0.5 bg-blue-600 transition-all duration-200 ${isActiveRoute('/homePage/homePageTenant') ? 'w-5' : 'w-0 group-hover:w-5'}`}></span>
              </button>
            </nav>
          </div>

          {/* 右侧：搜索框 + 消息通知 + 用户信息 */}
          <div class="flex items-center">
            {/* 搜索框 */}
            <div class="w-[408px] relative mr-[48px]" ref={searchContainerRef}>
              <div>
                <ElInput
                  v-model={searchKeyword.value}
                  placeholder="搜索课程、资源..."
                  class="w-full"
                  size="large"
                  onFocus={handleSearchFocus}
                  onKeydown={(e: Event | KeyboardEvent) => {
                    if (e instanceof KeyboardEvent && e.key === 'Enter') {
                      handleSearchEnter();
                    }
                  }}
                  v-slots={{
                    suffix: () => (
                      <VbenIconButton onClick={handleSearch}>
                        <Search class="w-[16px] h-[16px] text-[#595959]" />
                      </VbenIconButton>
                    )
                  }}
                />
              </div>

              {/* 搜索建议弹出框 */}
              <SearchSuggestion
                keyword={searchKeyword.value}
                visible={showSearchSuggestion.value}
                searchContainer={searchContainerRef.value}
                onUpdate:visible={(val: boolean) => showSearchSuggestion.value = val}
                onSelect={handleSearchSelect}
              />
            </div>

            {/* 消息通知 */}
            {isLogin.value && (
              <VbenIconButton class="bell-button cursor-pointer text-foreground relative" onClick={handleMessageClick}>
                {showDot.value && <span class="bg-[#E5484D] absolute right-0.5 top-0.5 h-2 w-2 rounded"></span>}
                <Bell class="text-[24px]" />
              </VbenIconButton>
            )}

            {/* 用户下拉菜单 */}
            <UserDropdown {...userDropdownProps.value} onLogout={handleLogout} />
          </div>
        </div>
      </div>
    );
  },
});
</script>

<style lang="less" scoped>
/* Custom styles for Element Plus components that need deep styling */
:deep(.el-input__wrapper) {
  border-radius: 9999px;
  transition: all 0.3s ease;
  box-shadow: none;
  background-color: #F3F3F3;

  &:hover {
    border-color: #60a5fa;
  }

  &.is-focus {
    border-color: #3b82f6;
  }
}

:deep(.el-input__suffix) {
  .el-button {
    border-radius: 0 9999px 9999px 0;
  }
}
</style>
